package com.ys.controller.api.outer;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ys.constant.AppConstant;
import com.ys.service.finance.TcwWanliPayoutService;
import com.ys.service.finance.TcwWanliTransferService;
import com.ys.util.wanli.WanliUtils;

/**
 * 万里汇回调接口
 */
@Controller
@RequestMapping("/api/outer/wfStore")
public class ApiOuterWfStoreController {
	@Autowired
	private TcwWanliPayoutService tcwWanliPayoutService;

    @Autowired
    private TcwWanliTransferService tcwWanliTransferService;

    private static final Logger logger = LoggerFactory.getLogger(ApiOuterWfStoreController.class);

    /*
     * 正式回调地址
     */
    @RequestMapping("/notifyFromWF")
    @ResponseBody
    public ResponseEntity<String> notifyFromWF(@RequestBody(required = false) String callbackData,HttpServletRequest request, HttpServletResponse response) {
        
    	/*
            头部host---admintest.mini-ease.com
            头部x-real-ip---47.235.21.194
            头部x-forwarded-for---47.235.21.194
            头部connection---upgrade
            头部content-length---922
            头部x-forwarded-by---Spanner-Sec-Proxy
            头部signature---algorithm=RSA256,keyVersion=1,signature=EQxXY%2Fd7Ng86S10o2z7DTiM%2Fq1FlFOVTn5pJxUdhK35Tg0uX%2FdEBDgVSUawL8pnSoCWcMh4rwBGJ9yjmT50k7vdnPl%2Fobhoiz6nfRzJZ5wYJGRs%2B6PcNaO9ljW1R9Z5dq0sM%2F5SfB0FES8ZlFh70Iv%2FTX%2FNa0PqY8hCkcODQtOYszG%2Bi8%2Fy3TDMGaxa5cbre%2BBINb%2BnkAT9WIzdTYS1hNDupYubfWgnHliUxQzxP78ukwl1ytQ4y7XuprarqDm%2BMrNO9bJrIVoyIQHavLoDi%2BFpJtXClv4SowGGWLUaU7x4tqbyjgTz3f7kvq08S2pHEGWOITmpD5TCPvX08Z%2F%2FDmw%3D%3D
            头部request-time---2024-06-24T06:41:20Z
            头部client-id---3J5Y8Y382Y3K3105035
            头部content-type---application/json
            头部group---alipay.net
            头部user-agent---Apache-HttpClient/4.5.6 (Java/1.8.0_332)
            头部accept-encoding---gzip,deflate
            头部x-decision-engine---marlin-decision-bypass
            请求体callbackData：{"transferFinishTime":"2024-06-24T06:41:19Z","transferFromDetail":{"transferFromAmount":{"currency":"EUR","value":5000},"transferFromMethod":{"customerId":"2120120007146804","paymentMethodType":"BALANCE"}},"transferId":"2024062419121000110800001911029","transferRequestId":"790df801-2e85-4f67-b540-7fedf12e5c02","transferResult":{"resultCode":"SUCCESS","resultMessage":"success.","resultStatus":"S"},"transferToDetail":{"feeAmount":{"currency":"EUR","value":10},"purposeCode":"GDS","transferNotifyUrl":"https://admintest.mini-ease.com/api/outer/wfStore/test4","transferQuote":{"quoteCurrencyPair":"EUR/CNY","quoteExpiryTime":"2024-06-24T06:40:17Z","quoteId":"20230929C50030530001336311","quotePrice":"7.70174920","quoteStartTime":"2023-09-29T07:42:55Z"},"transferToAmount":{"currency":"CNY","value":38432},"transferToMethod":{"paymentMethodId":"2024061819027700120305109984749","paymentMethodType":"BANK_ACCOUNT_DETAIL"}}}

    	 */
        Enumeration<String> headersName = request.getHeaderNames();
        String clientIdYq = "";
        String timeStringYq = "";
        String signatureYq = "";
        while(headersName.hasMoreElements()) {
        	String headerName = headersName.nextElement();
        	String headerValue = request.getHeader(headerName);
        	if (headerName.equals("client-id")){
                clientIdYq = headerValue;
            }
            if (headerName.equals("request-time")){
                timeStringYq = headerValue;
            }
            if (headerName.equals("signature")){
                String[] signatureList = headerValue.split("signature=");
                signatureYq = signatureList[1];
            }
            logger.info("万里汇回调头部" + headerName + "---" + headerValue);

        }


        /**
         * 验签
         */
        boolean verifyYq = false;
        String uriWithQueryStringYq = AppConstant.PATH_NOTIFY_WF;
        String  httpMethodYq = "POST";
        String contentYq = callbackData;
        try {
            verifyYq = WanliUtils.verifyHdYq(httpMethodYq, clientIdYq, uriWithQueryStringYq, timeStringYq, contentYq,signatureYq);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!verifyYq) {
            //验签失败 TODO
            logger.info("万里汇回调信息验签失败：" + callbackData);
            return null;
        }
        logger.info("万里汇回调信息验签成功!：");
        /*
         * {"transferFinishTime":"2024-06-20T06:04:22Z","transferFromDetail":{"transferFromAmount":{"currency":"EUR","value":6000},"transferFromMethod":{"customerId":"2120120007146804","paymentMethodType":"BALANCE"}},"transferId":"2024062019121000110800001887578","transferRequestId":"839798f7-8fcc-4da1-88af-ec8e8dd7a37c","transferResult":{"resultCode":"SUCCESS","resultMessage":"success.","resultStatus":"S"},"transferToDetail":{"feeAmount":{"currency":"EUR","value":12},"purposeCode":"GDS","transferNotifyUrl":"https://admintest.mini-ease.com/api/outer/wfStore/test4","transferQuote":{"quoteCurrencyPair":"EUR/CNY","quoteExpiryTime":"2024-06-20T06:01:09Z","quoteId":"20230929C50030530001336311","quotePrice":"7.70174920","quoteStartTime":"2023-09-29T07:42:55Z"},"transferToAmount":{"currency":"CNY","value":46118},"transferToMethod":{"paymentMethodId":"2024061819027700120086809996818","paymentMethodType":"BANK_ACCOUNT_DETAIL"}}}
         * {"transferFinishTime":"2024-06-24T02:51:02Z","transferFromDetail":{"transferFromAmount":{"currency":"EUR","value":5200},"transferFromMethod":{"customerId":"2120120007146804","paymentMethodType":"BALANCE"}},"transferId":"2024062419121000110800001909266","transferRequestId":"17383314-209e-472f-8bdf-1a08a50e55ec","transferResult":{"resultCode":"SUCCESS","resultMessage":"success.","resultStatus":"S"},"transferToDetail":{"feeAmount":{"currency":"EUR","value":10},"purposeCode":"GDS","transferNotifyUrl":"https://admintest.mini-ease.com/api/outer/wfStore/test4","transferQuote":{"quoteCurrencyPair":"EUR/CNY","quoteExpiryTime":"2024-06-24T02:50:15Z","quoteId":"20230929C50030530001336311","quotePrice":"7.70174920","quoteStartTime":"2023-09-29T07:42:55Z"},"transferToAmount":{"currency":"CNY","value":39972},"transferToMethod":{"paymentMethodId":"2024062419027700120409010056159","paymentMethodType":"BANK_ACCOUNT_DETAIL"}}}
         */
        logger.info("万里汇回调信息callbackData：" + callbackData);
        
        /*
         * 验证成功，并执行相应的逻辑
         */
        JSONObject resultJO = JSON.parseObject(callbackData);
        JSONObject transferResultJO = resultJO.getJSONObject("transferResult");
        if (transferResultJO.containsKey("resultCode")) {
			String resultCode = transferResultJO.getString("resultCode");
			if ("SUCCESS".equals(resultCode)) {
		        String transferRequestId = resultJO.getString("transferRequestId");
				try {
					tcwWanliPayoutService.changeToSuccess(transferRequestId);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
//
        // 解析callbackData并进行处理
        // 验证签名
        // 更新订单状态
        // 返回成功响应

        //响应体
        JSONObject jsonObject = new JSONObject();
        JSONObject resultStatus = new JSONObject();
        resultStatus.put("resultStatus","S");
        resultStatus.put("resultCode","SUCCESS");
        resultStatus.put("resultMessage","success");
        jsonObject.put("result",resultStatus);
        String content = JSONObject.toJSONString(jsonObject);

        HttpHeaders httpHeaders = WanliUtils.responseWanli(content, httpMethodYq, uriWithQueryStringYq, clientIdYq, "");

        return ResponseEntity.ok().headers(httpHeaders).body(content);
    }


    @RequestMapping("/test5")
    @ResponseBody
    public void test5(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String[]> requestParams = request.getParameterMap();
        logger.info("万里汇回调信息：" + JSON.toJSONString(requestParams));
    }

    @RequestMapping("/test6")
    @ResponseBody
    public void test6(
    		@RequestBody String body,
    		HttpServletRequest request,
    		HttpServletResponse response) {
        Map<String, String[]> requestParams = request.getParameterMap();
        logger.info("万里汇回调信息requestParams：" + JSON.toJSONString(requestParams));
        logger.info("万里汇回调信息callbackData：" + body);
        logger.info("万里汇回调信息response：" + response);
        // 解析callbackData并进行处理
        // 验证签名
        // 更新订单状态
        // 返回成功响应
        try {
			response.getWriter().print("success");
		} catch (IOException e) {
			e.printStackTrace();
		}
//        return ResponseEntity.ok("success");
    }

    @RequestMapping("/test3")
    @ResponseBody
    public ResponseEntity<String> test3(@RequestBody(required = false) String callbackData,HttpServletRequest request, HttpServletResponse response) {
        Map<String, String[]> requestParams = request.getParameterMap();
        logger.info("万里汇回调请求notifyTransfer：" + JSON.toJSONString(request));
        logger.info("万里汇回调头部notifyTransfer：" + JSON.toJSONString(request.getHeaderNames()));
        logger.info("万里汇回调信息requestParams：" + JSON.toJSONString(requestParams));

        /*
         * {"transferFinishTime":"2024-06-20T06:04:22Z","transferFromDetail":{"transferFromAmount":{"currency":"EUR","value":6000},"transferFromMethod":{"customerId":"2120120007146804","paymentMethodType":"BALANCE"}},"transferId":"2024062019121000110800001887578","transferRequestId":"839798f7-8fcc-4da1-88af-ec8e8dd7a37c","transferResult":{"resultCode":"SUCCESS","resultMessage":"success.","resultStatus":"S"},"transferToDetail":{"feeAmount":{"currency":"EUR","value":12},"purposeCode":"GDS","transferNotifyUrl":"https://admintest.mini-ease.com/api/outer/wfStore/test4","transferQuote":{"quoteCurrencyPair":"EUR/CNY","quoteExpiryTime":"2024-06-20T06:01:09Z","quoteId":"20230929C50030530001336311","quotePrice":"7.70174920","quoteStartTime":"2023-09-29T07:42:55Z"},"transferToAmount":{"currency":"CNY","value":46118},"transferToMethod":{"paymentMethodId":"2024061819027700120086809996818","paymentMethodType":"BANK_ACCOUNT_DETAIL"}}}
         */
        logger.info("万里汇回调信息(notifyTransfer)callbackData：" + callbackData);
        logger.info("万里汇回调信息(notifyTransfer)response：" + response);
        // 解析callbackData并进行处理
        // 验证签名
        // 更新订单状态
        // 返回成功响应

        //响应体
        JSONObject jsonObject = new JSONObject();
        JSONObject resultStatus = new JSONObject();
        resultStatus.put("resultStatus","S");
        resultStatus.put("resultCode","SUCCESS");
        resultStatus.put("resultMessage","success");
        jsonObject.put("result",resultStatus);
        logger.info("万里汇回调信息jsonObjectt：" + jsonObject);
        String content = JSONObject.toJSONString(jsonObject);

        String clientId = "3J5Y8Y382Y3K3105035";
        String uriWithQueryString = "/api/outer/wfStore/test3";
        String httpMethod = "POST";
        logger.info("万里汇回调信息(notifyTransfer)uriWithQueryString：" + uriWithQueryString);
        HttpHeaders httpHeaders = WanliUtils.responseWanli(content, httpMethod, uriWithQueryString, clientId, "");

        return ResponseEntity.ok().headers(httpHeaders).body(content);
    }


    /**
     * 万里汇createTransfer 主转子回调
     * @param callbackData
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/test8")
    @ResponseBody
    public ResponseEntity<String> test8(@RequestBody(required = false) String callbackData,HttpServletRequest request, HttpServletResponse response) {

        Enumeration<String> headersName = request.getHeaderNames();
        String clientIdYq = "";
        String timeStringYq = "";
        String signatureYq = "";
        while(headersName.hasMoreElements()) {
            String headerName = headersName.nextElement();
            String headerValue = request.getHeader(headerName);
            if (headerName.equals("client-id")){
                clientIdYq = headerValue;
            }
            if (headerName.equals("request-time")){
                timeStringYq = headerValue;
            }
            if (headerName.equals("signature")){
                String[] signatureList = headerValue.split("signature=");
                signatureYq = signatureList[1];
            }
            logger.info("万里汇主转子回调头部" + headerName + "---" + headerValue);

        }


        /**
         * 验签
         */
        boolean verifyYq = false;
        String uriWithQueryStringYq = "/api/outer/wfStore/test8";
        String  httpMethodYq = "POST";
        String contentYq = callbackData;
        try {
            verifyYq = WanliUtils.verifyHdYq(httpMethodYq, clientIdYq, uriWithQueryStringYq, timeStringYq, contentYq,signatureYq);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!verifyYq) {
            //验签失败 TODO
            logger.info("万里汇回调主转子信息验签失败：" + callbackData);
            return null;
        }
        logger.info("万里汇主转子回调信息验签成功!：");

        logger.info("万里汇主转子回调信息callbackData：" + callbackData);

        /*
         * 验证成功，并执行相应的逻辑
         */
        JSONObject resultJO = JSON.parseObject(callbackData);
        JSONObject transferResultJO = resultJO.getJSONObject("transferResult");
        if (transferResultJO.containsKey("resultCode")) {
            String resultCode = transferResultJO.getString("resultCode");
            if ("SUCCESS".equals(resultCode)) {
                String transferRequestId = resultJO.getString("transferRequestId");
                try {
                    tcwWanliTransferService.changeToSuccess(transferRequestId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
//
        // 解析callbackData并进行处理
        // 验证签名
        // 更新订单状态
        // 返回成功响应

        //响应体
        JSONObject jsonObject = new JSONObject();
        JSONObject resultStatus = new JSONObject();
        resultStatus.put("resultStatus","S");
        resultStatus.put("resultCode","SUCCESS");
        resultStatus.put("resultMessage","success");
        jsonObject.put("result",resultStatus);
        String content = JSONObject.toJSONString(jsonObject);

        HttpHeaders httpHeaders = WanliUtils.responseWanli(content, httpMethodYq, uriWithQueryStringYq, clientIdYq, "");

        return ResponseEntity.ok().headers(httpHeaders).body(content);
    }
}
